package com.zhang.service;
import com.alibaba.fastjson.JSON;
import com.zhang.entity.ChannelBody;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetAddress;

/**
 * User: 张
 * Date: 2024-11-15
 * Time: 19:17
 * Description:
 */
@Component
public class IoTNettyClient {
    private final EventLoopGroup group = new NioEventLoopGroup();
    private static Channel channel;
    @Value("${netty.client.host}")
    private String host; // 服务端主机地址
    @Value("${netty.client.port}")
    private int port; // 服务端端口
    @Autowired
    private AsyncService asyncService;
    @PostConstruct
    public void start() throws InterruptedException {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new IoTClientHandler());
                    }
                });

        channel = b.connect(host, port).sync().channel();
        System.out.println("IoT Netty客户端设备连接到服务端 ip: " + host + ":" + port);
        try {
            sendMessageToServer(JSON.toJSONString(new ChannelBody(0, InetAddress.getLocalHost().getHostAddress())));
        }catch (Exception e){
            throw new RuntimeException("获取本机ip地址异常");
        }
    }
    public static void sendMessageToServer(String message) {
        if (channel != null && channel.isActive()) {
            ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes());
            channel.writeAndFlush(byteBuf);
        } else {
            System.out.println("IoT Netty客户端未连接到服务端");
        }
    }
    @PreDestroy
    public void stop() throws InterruptedException {
        if (channel != null) {
            channel.close().sync();
            System.out.println("IoT Netty客户端与服务器断开连接");
        }
        group.shutdownGracefully();
        System.out.println("IoT Netty客户端事件循环组关闭");
    }
    private class IoTClientHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            System.out.println("客户端处于活动状态并已连接到服务器 当前id为："+ctx.channel().id());
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) {
            System.out.println("客户端已与服务器断开连接");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof ByteBuf) {
                ByteBuf buf = (ByteBuf) msg;
                // 确保ByteBuf有足够的可读字节
                if (buf.isReadable()) {
                    // 将ByteBuf转换为字符串
                    String receivedMessage = buf.toString(io.netty.util.CharsetUtil.UTF_8);
                    System.out.println("从服务器收到消息: " + receivedMessage);
                    asyncService.executeScript(receivedMessage);
                    // 释放ByteBuf内存
                    buf.release();
                }
            } else {
                super.channelRead(ctx, msg);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            System.out.println("服务端异常");
            ctx.close();
        }
    }




}
